<script lang="ts" setup>
import { computed, ref, toRaw } from 'vue';
import { Delete } from '@element-plus/icons-vue';
import { useTextStore } from "@/stores/config/configTextStore"
import { useSettingStore } from '@/stores/settingStore'
import { ConfigDataType } from '@/utils/enum'
import { typeNames, type ConfigCol, type ConfigTableHeader, type TableRow } from '@/utils/struct'
import ConfigTableElementSelectDialog from '../dialog/ConfigTableElementSelectDialog.vue';
import type { ElInput, ElInputNumber } from 'element-plus';
import { nextTick } from "vue"
import { useTablePageStore } from '@/stores/config/tablePageStore';
import { ViewHelper } from '@/utils/viewHelper';
const electron = require('electron')
let textStore = useTextStore()
let settingStore = useSettingStore()
let pageStore = useTablePageStore()
// 0~n是表个的行，-1 -2 -3是表名/描述/键值，-4表示未选中任何需要编辑的内容
const emptyRow = -4
let editingRow = ref(emptyRow);
let editingCol = ref(-1);
let inputRef = ref<InstanceType<typeof ElInput> | null>(null);
let numberInputRef = ref<any | null>(null);

let tableElementSelectId = ref(0)

let showNewColDialog = ref(false)

let showTextSelect = ref(false)
let showTableElementSelect = ref(false)
// 新增分页变量
const currentPage = ref(1)
const pageSize = ref(10)

// 新增分页数据计算
const currentPageElements = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return pageStore.selectedTable?.rows.slice(start, start + pageSize.value) || []
})
let startEdit = function (row: number, col: number) {
    editingRow.value = row;
    editingCol.value = col;

    if (row < 0) {
        nextTick(() => {
            inputRef?.value?.focus()
        })
        return
    }
    let table = pageStore.selectedTable
    if (!table) return
    let header = table.tableHeader[col]
    if (header.type == ConfigDataType.Integer) {
        nextTick(() => {
            // 实测这里需要写value[0] 并且上面的类型用ElNumberInput会报错，所以用any了
            numberInputRef.value[0].focus()
        })
    } else if (header.type == ConfigDataType.String) {
        showTextSelect.value = true;
    }
}

let closeEdit = function () {
    editingRow.value = emptyRow;
    editingCol.value = -1;
}

let changeContent = function (rowIdx: number, colIdx: number) {
    let table = pageStore.selectedTable
    if (!table) return
    let row = table.rows[rowIdx]
    electron.ipcRenderer.send("changeTableContent", table.id, row.id, colIdx, row.values[colIdx])
}

let isEditing = function (row: number, col: number) {
    return editingRow.value == row && editingCol.value == col;
}
let onCurrentChange = function (row: any) {
    if (row) {
        pageStore.selectedRowId = row.id;
    } else {
        pageStore.selectedRowId = 0;
    }
}
let addCurPageRow = function () {
    pageStore.addCurTableRow()
    // configStore.addCurTableRow()
}
let addNewCol = function () {
    showNewColDialog.value = true;
}

let onConfirm = function (id: number) {
    showTextSelect.value = false;
    if (id) {
        let table = pageStore.selectedTable
        if (!table) return
        currentPageElements.value[editingRow.value].values[editingCol.value] = id
    }
    closeEdit()
}

let onConfirmNewCol = function (col: ConfigCol) {
    let header = pageStore.addCurTableCol(col)
    showNewColDialog.value = false
}

let getElementText = function (header: ConfigTableHeader, value: number) {
    return ViewHelper.getTableElementText(header, value)
}

let selectTableElement = function (row: number, col: number) {
    editingRow.value = row;
    editingCol.value = col;
    let table = pageStore.selectedTable
    if (!table) return
    tableElementSelectId.value = table.tableHeader[col].quoteId
    showTableElementSelect.value = true
}

let onConfirmElementSelect = function (id: number) {
    let table = pageStore.selectedTable
    if (!table) return
    currentPageElements.value[editingRow.value].values[editingCol.value] = id
    showTableElementSelect.value = false
    editingCol.value = -1
    editingRow.value = emptyRow
}

let parseContent = (header: ConfigTableHeader, row: TableRow, colIndex: number) => {
    if (header.type == ConfigDataType.Integer || header.type == ConfigDataType.Float) {
        return row.values[colIndex].toString()
    } else if (header.type == ConfigDataType.String) {
        return textStore.getTextById(row.values[colIndex])
    }
}
let deleteRow = function (row: number) {
    pageStore.deleteCurTableRow(row)
}
let deleteTableCol = function (id: number) {
    pageStore.deleteCurTableCol(id)
}
let changeHeaderExportGroup = function (headerId: number) {
    let table = pageStore.selectedTable
    if (!table) return
    let header = table.tableHeader.find(h => h.id == headerId)
    if (!header) return
    electron.ipcRenderer.send("changeTableHeaderExportGroup", table.id, headerId, toRaw(header.exportGroups))
}
let changeTableExportGroups = () => {
    let table = pageStore.selectedTable
    if (!table) return
    electron.ipcRenderer.send("changeTableExportGroup", table.id, toRaw(table.exportGroups))
}

let changeGroupId = (row: TableRow, index: number, newId: number)=>{
    let table = pageStore.selectedTable
    if (!table) return;
        row.values[index] = newId;
        electron.ipcRenderer.send('changeTableContent', table.id, row.id, index, newId)
}
</script>

<template>
    <div v-if="pageStore.selectedTable != null">

        <!-- 表格名称 -->
        <div>
            <el-text size="large">{{ "表格名称：" }}</el-text>
            <el-button type="primary" link v-if="editingRow != -1" @click="startEdit(-1, 0)">{{
                pageStore.selectedTable.name }}</el-button>
            <el-input v-model="pageStore.selectedTable.name" v-if="editingRow == -1" @blur="closeEdit"
                @keyup.enter="closeEdit" ref="inputRef" style="display: inline-block;width:auto"></el-input>
        </div>
        <!-- 表格描述 -->
        <div>
            <el-text size="large">{{ "表格描述：" }}</el-text>
            <el-button type="primary" link v-if="editingRow != -2" @click="startEdit(-2, 0)">{{
                pageStore.selectedTable.desc }}</el-button>
            <el-input v-model="pageStore.selectedTable.desc" v-if="editingRow == -2" @blur="closeEdit"
                @keyup.enter="closeEdit" ref="inputRef" style="display: inline-block;width:auto"></el-input>
        </div>
        <!-- key -->
        <div>
            <el-text size="large">{{ "key：" }}</el-text>
            <el-button type="primary" link v-if="editingRow != -3" @click="startEdit(-3, 0)">{{
                pageStore.selectedTable.key }}</el-button>
            <el-input v-model="pageStore.selectedTable.key" v-if="editingRow == -3" @blur="closeEdit"
                @keyup.enter="closeEdit" ref="inputRef" style="display: inline-block;width:auto"></el-input>
        </div>
        <!-- 导出分组 -->
        <div>
            <el-select multiple v-model="pageStore.selectedTable.exportGroups" @change="changeTableExportGroups()">
                <el-option v-for="item in settingStore.exportGroups" :key="item.id" :label="item.name"
                    :value="item.id"></el-option>
            </el-select>
        </div>
        <el-table :data="currentPageElements" stripe border highlight-current-row
            @current-change="onCurrentChange">

            <el-table-column width="100">
                <template #header>
                    <el-tooltip class="box-item" effect="dark" content="仅用于编辑工具中显示" placement="top-start">
                        <el-text>列名</el-text>
                    </el-tooltip>
                </template>
                <el-table-column>
                    <template #header>
                        <el-text>key</el-text>
                    </template>
                    <el-table-column>
                        <template #header>
                            <el-text>导出分组</el-text>
                        </template>
                        <template #default="scope">
                            <el-text>{{ scope.row.id }}</el-text>
                        </template>
                    </el-table-column>

                </el-table-column>

            </el-table-column>
            <el-table-column v-for="(item, index) in pageStore.selectedTable.tableHeader" :key="index" width="180">
                <template #header>
                    <el-text>{{ item.label }}</el-text>
                    <el-button link type="danger" :icon="Delete" @click="deleteTableCol(item.id)"></el-button>
                </template>
                <el-table-column :label="item.key">
                    <template #header>
                        <el-button link type="primary">{{ item.key }}</el-button>
                    </template>
                    <el-table-column>
                        <template #header>
                            <el-select multiple v-model="item.exportGroups" @change="changeHeaderExportGroup(item.id)">
                                <el-option v-for="item in settingStore.exportGroups" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </template>
                        <template #default="scope">
                            <!-- 表格内容 -->
                            <el-button style="width: 100%;"
                                v-if="(item.type == ConfigDataType.Integer || item.type == ConfigDataType.String || item.type == ConfigDataType.Float) && !isEditing(scope.$index, index)"
                                type="primary" link @click="startEdit(scope.$index, index)">{{ parseContent(item,
                                    scope.row, index) }}</el-button>

                            <!-- 布尔值类型，直接显示成一个开关 -->
                            <el-switch v-if="item.type == ConfigDataType.Boolean" v-model="scope.row.values[index]"
                                :active-value=1 :inactive-value=0
                                @change="changeContent(scope.$index, index)"></el-switch>
                            <!-- 整数类型，开始编辑后显示 -->
                            <el-input-number v-model="scope.row.values[index]" step-strictly :step="1"
                                v-if="item.type == ConfigDataType.Integer && isEditing(scope.$index, index)"
                                @blur="closeEdit()" ref="numberInputRef"></el-input-number>
                            <!-- 浮点数类型，开始编辑后显示 -->
                            <el-input-number v-model="scope.row.values[index]" step-strictly :step="0.1"
                                v-if="item.type == ConfigDataType.Float && isEditing(scope.$index, index)" @blur="closeEdit()"
                                ref="numberInputRef"></el-input-number>
                            <!-- 引用类型，点击打开弹窗选择引用 -->
                            <el-button v-if="item.type == ConfigDataType.Quote"
                                @click="selectTableElement(scope.$index, index)">
                                {{ getElementText(item, scope.row.values[index]) }}</el-button>
                        </template>
                    </el-table-column>


                </el-table-column>
            </el-table-column>
            <el-table-column width="100px">
                <template #header>
                    <el-button @click="addNewCol()">添加</el-button>
                </template>
                <template #default="scope">
                    <el-button link type="danger" :icon="Delete" @click="deleteRow(scope.$index)"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-button style="width:100%" @click="addCurPageRow()">添加</el-button>
                <!-- 在表格下方添加分页组件 -->
        <el-pagination
            layout="prev, pager, next"
            :total="pageStore.selectedTable.rows.length"
            v-model:current-page="currentPage"
            :page-size="pageSize"
            style="margin-top: 15px;">
        </el-pagination>
        <ConfigTableColCreateView v-model="showNewColDialog" @confirm="onConfirmNewCol"></ConfigTableColCreateView>
        <TextSelectDialog v-model="showTextSelect" @confirm="onConfirm"></TextSelectDialog>
        <ConfigTableElementSelectDialog :tableId="tableElementSelectId" v-model="showTableElementSelect"
            @confirm="onConfirmElementSelect"></ConfigTableElementSelectDialog>
    </div>
</template>
